use rbatis::{crud, impled, py_sql, RBatis};
use rbatis::executor::Executor;
use crate::domain::dto::module_dto::ModulePageResponse;
use crate::domain::entity::module_entity::ModuleEntity;

/// ModuleEntity 数据模型基础查询
crud!(ModuleEntity {}, "api_module");

#[py_sql("`select count(t.id) from api_module as t where t.biz_id=#{biz_id}`")]
pub async fn count_by_biz_id(rb: &mut dyn Executor, biz_id: u64) -> rbatis::Result<u64> {
    impled!()
}

/// select_module_page 分页查询
#[py_sql("`select `
    `am.id,`
    `am.module_name as name,`
    `am.module_desc as desc,`
    `am.biz_id,`
    `(select ab.biz_name from api_biz ab where ab.id = am.biz_id) as biz_name,`
    `am.owner `
`from api_module am where 1 = 1 `
if name != '':
    ` and am.module_name like concat('%', #{name}, '%') `
if biz_id != 0:
    ` and am.biz_id = #{biz_id} `
` order by am.module_name asc limit #{size} offset #{num}`")]
pub async fn select_module_page(rb: &mut dyn Executor, num: u64, size: u64, name: Option<String>, biz_id: Option<u64>) -> rbatis::Result<Vec<ModulePageResponse>> {
    impled!()
}

/// select_module_count 分页统计
#[py_sql("select count(1) from api_module am where 1 = 1 `
if name != '':
    ` and am.module_name = #{name} `
if biz_id != 0:
    ` and am.biz_id = #{biz_id} ")]
pub async fn select_module_count(rb: &mut dyn Executor, name: Option<String>, biz_id: Option<u64>) -> rbatis::Result<u64> {
    impled!()
}

#[py_sql("`select count(1) from api_module am where am.module_name = #{name}`
if id != 0:
    ` and am.id != #{id}`")]
async fn get_same_name_num(rb: &mut dyn Executor, name: &str, id: Option<u64>) -> rbatis::Result<u64> {
    impled!()
}

pub async fn exit_same_name(rb: &mut dyn Executor, name: &str, id: Option<u64>) -> rbatis::Result<bool> {
    let result = get_same_name_num(rb, name, id).await;
    match result {
        Ok(v) => { if v > 0 { Ok(true) } else { Ok(false) } },
        Err(e) => {
            tracing::error!("查询是否有相同的模型名称: {}", e);
            Ok(false)
        }
    }
}

#[py_sql("`select * from api_module am where am.id = #{id}`")]
pub async fn select_one_by_id(p0: &mut RBatis, id: u64) -> rbatis::Result<ModuleEntity> {
    impled!()
}